import Vue from 'vue';
import TaskDetailView from './TaskDetailView.vue';

import { Loading } from 'element-ui';
import { getAsyncTaskViewInitData } from '@src/api/InitDataApi'
import qs from 'qs';
import platform from '@src/platform';
import { useMapType } from '@src/util/map'
import { MapTypeEnum } from '@model/enum/MapEnum'
import {getRootWindow} from "@src/util/dom";
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'
import {getTaskFlowNode} from "@src/api/SettingTaskApi";



const componentItem = (initData, maptype, instance, taskALlNode) => {
  return {
    provide: {
      initData: Object.freeze(initData),
      currentMapType:maptype,
      taskALlNode: taskALlNode,
    },
    data() {
      return {
        instance
      }
    },
    render(h) {
      return h(TaskDetailView, {
        on: {
          changeLoading: (open) => {
            if (open) {
              this.instance = Loading.service({ fullscreen: true });
            } else {
              this.instance.close();
            }
          }
        }
      });
    }
  }
}

Vue.component('async-component', function(resolve) {
  
  // 需要加loading 打开此注释
  const instance = Loading.service({ fullscreen: true });
  
  let query = qs.parse(window.location.search.substr(1));
  const url = window.location.href;
  const index = url.lastIndexOf('/');
  const id = url.substring(index + 1, url.length).split('?')[0];
  const params = Object.assign({}, query, {id})

  const taskFlowExtend = getRootWindow(window)?.grayAuth?.[GrayFunctionEnum.TaskFlowExtend] ?? false // 工单流程节点灰度

  getAsyncTaskViewInitData(params).then(async (result) => {
    let mapType = MapTypeEnum.AMap
    let taskALlNode = []
    try{
      const { currentMapType } = await useMapType();
      mapType = currentMapType()
    }catch (err){
      console.error('try catch currentMapType ->', err)
    }

    // 获取工单节点流程
    if(taskFlowExtend) {
      try {
        const { result } = await getTaskFlowNode({taskId: params.id});
        taskALlNode = result
      } catch (e) {
        console.error(e)
      }
    }

    let initData = result?.data?.initJson || {}
    // 工单草稿状态处理
    if (initData.task?.state && initData.task?.isDelete == 5) {
      initData.task.state = 'draft'
    }
    const title = (result && result.data && result.data.title) || ''
    const isSuccess = result.succ || result.success
    if (!isSuccess) {
      window.location.href = '/500'
      return 
    }
    
    try {
      window._init = JSON.stringify(initData)
    } catch (error) {
      console.error('initData 赋值失败')
    }
    
    
    if (window.frameElement) {
      const currentTabId = window.frameElement.dataset.id;
      platform.setTabTitle({
        id: currentTabId,
        title
      })
    }
    resolve(componentItem(initData, mapType, instance, taskALlNode))
    
  }).catch(error => {
    console.error(error)
    window.location.href = '/500'
  })
  
});

let app = {
  render(h) {
    return <async-component />
  }
}

export default app;
